//
//  HomeStatusRefresh.swift
//  weibopush
//
//  Created by 龚欣 on 15/7/2.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import FFAutoLayout


class HomeStatusRefresh: UIRefreshControl {

   private var showTipFlag = false
    var loadingFlag = false
    
    override init() {
        super.init()
        
        addSubview(refreshView)

        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 142, height: 60))
        
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }

        // 如果正在加载数据，就显示加载动画
        if refreshing && !loadingFlag {
            refreshView.startFreshIconAnimation()
            
            loadingFlag = true
            return
        }
        
        if frame.origin.y < -50 && !showTipFlag {
            showTipFlag = true
            refreshView.rotateTipIcon(showTipFlag)
        } else if frame.origin.y >= -50 && showTipFlag {
            showTipFlag = false
            refreshView.rotateTipIcon(showTipFlag)
        }
        
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        loadingFlag = false
        refreshView.endFreshIconAnimation()
    }
    
    

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   lazy var refreshView = RefreshView.refreshView()
}

class RefreshView : UIView {
 /// 上面盖的view，通过隐藏和显示切换
    @IBOutlet weak var tipView: UIView!
 /// 转的圆圈
    @IBOutlet weak var freshIcon: UIImageView!
 /// 箭头
    @IBOutlet weak var tipIcon: UIImageView!
    
    private class func refreshView() -> RefreshView{
       return NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView
    }
    
    private func rotateTipIcon(closeWise : Bool){
        var angle = M_PI
        angle += closeWise ? +0.01 : -0.01
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform,CGFloat(angle))
        }
    }
    
    private func startFreshIconAnimation(){
        tipView.hidden = true
        
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.duration = 0.5
        animation.repeatCount = MAXFLOAT
        animation.toValue = M_PI * 2
        
        freshIcon.layer.addAnimation(animation, forKey: nil)
    }
    
    private func endFreshIconAnimation(){
        tipView.hidden = false
        freshIcon.layer.removeAllAnimations()
    
    }
    
}